package com.summer.ioc.util;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @author xiaoye
 * @create 2021-05-02 22:41
 */
public class ClassUtil {

    public static final List<Class> wrapTypes =
            List.of(Integer.class,
                    Short.class,
                    Byte.class,
                    Long.class,
                    Float.class,
                    Double.class,
                    Boolean.class,
                    Character.class);

    public static boolean isSynthetic(Class<?> c)
    {
        return c.isSynthetic();
    }

    // 是否是包装类型
    public static boolean isWrap(Class<?> c)
    {
        return wrapTypes.contains(c);
    }

    public static List<Class<?>> getClassesByPackageNames(String[] packageNames)
    {
        List<Class<?>> list = new ArrayList<>();

        for (String packageName : Set.of(packageNames)) {
            list.addAll(getClassesByPackageName(packageName));
        }
        return list;
    }

    public static List<Class<?>> getClassesByPackageName(String packageName)
    {
        String classPath = FileUtil.getClassPath();
        String packagePath = packageName.replaceAll(".", File.separator);
        File packageFile = new File(classPath,packagePath);
        List<Class<?>> list = new ArrayList<>();
        getClassesByPackageName(packageName,packageFile,list);
        return list;
    }

    private static void getClassesByPackageName(String packageName, File file, List<Class<?>> list) {
        if (file.isDirectory())
        {
            Arrays.stream(file.listFiles()).forEach((file1)->{
                getClassesByPackageName(packageName+"."+file.getName(),file1,list);
            });
        }
        else if (file.isFile() && FileUtil.getExtensionName(file).equals(".class"))
        {
            String className = packageName + "." + FileUtil.getFileNameWithoutExtensionName(file);
            try {
                list.add(Class.forName(className));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}
